// pages/addCertificate/addCertificate.js
var app = getApp();
var util = require("../../utils/util.js");
var siteinfo = require('../../siteinfo.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        jobtype: '', // 工种
        level: '',// 等级
        zsNumber: '',// 证书号
        time: '',// 发证日期
        timeShow: '',// 结束时间显示隐藏
        recordCertificate: '', //学历证书 
        imagesXueli: '/image/addPic.png',
        token: '',
        datalist: {},
        endDate:'',
        birthTime:''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.calculateDateRange()
        this.setData({
            datalist: JSON.parse(options.datalist)
        })
        this.handleGetDataList()
    },
    calculateDateRange: function () {
        const now = new Date();
        const year = now.getFullYear();
        const month = now.getMonth() + 1;
        const day = now.getDate();
        // 计算最大可选日期（18年前）
        const maxDate = `${year}-${this.formatDate(month)}-${this.formatDate(day)}`;
        this.setData({
            endDate: maxDate,
            birthTime:maxDate,
        });
    },
    // 删除证书
    handleDetele: function (params) {
        let token = wx.getStorageSync('token');
        wx.request({
            url: siteinfo.siteroot3 + 'jzApi/certificateInfo/remove',
            header: {
                'Authorization': token,
                'content-type': 'application/json'
            },
            method: 'GET',
            data: {
                id: this.data.datalist.id
            },
            success: function (res) {
                if (res.data.code == '0') {
                    wx.showToast({
                        title: '删除成功',
                        icon: 'success',
                        duration: 2000
                      })
                    // console.log(res);
                    setTimeout(() => {
                        if (res.data.code == '0') {
                            wx.navigateBack({
                                url: '/pages/xinxiLuru/xinxilu'
                            })
                    }
                    }, 500);
                }
                return false;
            }
        });
    },
    //选择出生年月
    bindDateChange: function (e) {
        this.setData({
            time: e.detail.value
        })
    },
    handleGetDataList: function (params) {
        if (this.data.datalist.career) {
            wx.setNavigationBarTitle({
                title: '编辑证书'
            })
            this.setData({
                jobtype: this.data.datalist.career, // 工种
                level: this.data.datalist.level,// 等级
                zsNumber: this.data.datalist.number,// 证书号
                time: this.data.datalist.certificateTime,// 发证日期
                recordCertificate: this.data.datalist.photo, //学历证书 
                imagesXueli: this.data.datalist.photo,
            })
        }
     
    },
    // 获取等级
    getLevel(e) {
        var value = e.detail.value;
        this.setData({
            level: value
        });
    },
    // 获取职业
    getJobtype(e) {
        var value = e.detail.value;
        this.setData({
            jobtype: value
        });
    },
    // 获取证书号
    getZsNumber(e) {
        var value = e.detail.value;
        this.setData({
            zsNumber: value
        });
    },

    // 日历组件
    onStatTimeDisplay() {
        this.setData({ timeShow: true });
    },
    onStatTimeClose() {
        this.setData({ timeShow: false });
    },
    onStatTimeConfirm(event) {
        this.setData({
            timeShow: false,
            time: this.formatDate(event.detail),
        });
    },
    formatDate(date) {
        date = new Date(date);
        return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
    },
    chooseImageXueli(e) { //学历证书
        var _this = this
        wx.chooseImage({
            sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
            sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
            success: res => {
                console.log(res);
                if (res.tempFiles[0].size < 5242880) {
                    wx.getImageInfo({
                        src: res.tempFilePaths[0],
                        success(result) {
                            const tempFilePaths = res.tempFilePaths
                            app._uploadFile(siteinfo.fileImprot,
                                res.tempFiles[0].path,
                                'file', {
                                name: res.tempFiles[0].name
                            },
                                function (res1) {
                                    _this.setData({
                                        recordCertificate: res1.data,
                                        imagesXueli: tempFilePaths,
                                    })
                                })
                        }
                    })
                } else {
                    app.showError('寸照应小于5M！')
                }
            }
        })
    },


    // 保存
    handleSave: function (e) {
        console.log(this.data.jobtype);
        if (!this.data.jobtype) {
            app.showError('请输入职业!')
            return false;
        }
        if (!this.data.level) {
            app.showError('请输入等级!')
            return false;
        }
        if (!this.data.zsNumber) {
            app.showError('请输入证书号!')
            return false;
        }
        if (!this.data.time) {
            app.showError('请选择发证日期!')
            return false;
        }
        if (!this.data.recordCertificate) {
            app.showError('上传图片证书!')
            return false;
        }
        let token = wx.getStorageSync('token');
        let requrl = siteinfo.siteroot3 + 'jzApi/certificateInfo/saveUserCertificate'
        let tishimsg='添加成功!'
        if (this.data.datalist.career) {
            requrl = siteinfo.siteroot3 + 'jzApi/certificateInfo/updateUserCertificate'
            tishimsg='编辑成功!'
        }
        wx.request({
            url: requrl,
            header: {
                'Authorization': token,
                'content-type': 'application/json'
            },
            method: 'POST',
            data: {
                id: this.data.datalist.id,
                career: this.data.jobtype,
                level: this.data.level,
                number: this.data.zsNumber,
                photo: this.data.recordCertificate,
                certificateTime: this.data.time
            },
            success: function (res) {
                wx.showToast({
                    title: tishimsg,
                    icon: 'success',
                    duration: 2000
                  })
                // console.log(res);
                setTimeout(() => {
                    if (res.data.code == '0') {
                    wx.navigateBack({
                        url: '/pages/xinxiLuru/xinxilu'
                    })
                }
                }, 500);
            }
        });

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        wx.getStorageSync({
            key: 'token',
            success(res) {
                this.setData({
                    token: res.data
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        wx.getStorageSync({
            key: 'token',
            success(res) {
                this.setData({
                    token: res.data
                })
            }
        })
        this.handleGetDataList()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})